#!/bin/bash

# 编译驱动或应用
# 用法 ：./build -a(应用)  or   ./build -d(驱动)

# 定义 tftp 目录
TFTP_DIR="/home/nixiak/linux/tftp"  

# 检查是否有参数
if [ $# -lt 1 ]; then
  echo "Usage: \$0 -<option>"
  echo "Options:"
  echo "  -d  Build the driver project"
  echo "  -a  Build the app project"
  exit 1
fi

function find_executable_or_ko() {
    for files in *; do
        if ls "$files" | grep -q ".ko";then
            echo "$files"
            break
        elif file "$files" | grep -q "ELF"; then
            echo "$files"
            break
        fi
    done
}

# 根据传入的参数执行相应操作
while getopts ":da" option; do
  case $option in
    d)
      # 进入 driver 目录并执行 make
      echo "Entering ./driver directory..."
      cd ./driver || { echo "Failed to enter ./driver directory"; exit 1; }
      make || { echo "Make command failed in ./driver"; exit 1; }
      # 复制编译后的文件到 tftp 目录
      output_file=$(find_executable_or_ko)
      echo "$output_file"
      cp $output_file $TFTP_DIR || { echo "Failed to copy file to tftp"; exit 1; }
      echo "Successful to Compiled and Copy!"
      ;;
    a)
      # 进入 app 目录并执行 make
      echo "Entering ./app directory..."
      cd ./app || { echo "Failed to enter ./app directory"; exit 1; }
      make || { echo "Make command failed in ./app"; exit 1; }
      # 复制编译后的文件到 tftp 目录
      output_file=$(find_executable_or_ko)
      echo "$output_file"
      cp "$output_file" $TFTP_DIR || { echo "Failed to copy file to tftp"; exit 1; }
      echo "Successful to Compiled and Copy!"
      # ls -l | grep ".ko"
      ;;
    *)
      echo "Invalid option. Usage: \$0 -<option>"
      exit 1
      ;;
  esac
done

exit 0
